package com.le.tester.leetcode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * createTime：2024/4/25 14:19
 * description：候选组合
 */
public class CombinationSum {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {

        int length = candidates.length;
        List<List<Integer>> res = new ArrayList<>();

        if (length == 0) {
            return res;
        }

        Deque<Integer> path = new ArrayDeque<>();

        dfs(candidates, 0, length, target, path, res);
        return res;

    }

    private void dfs(int[] candidates, int begin, int length, int target, Deque<Integer> path, List<List<Integer>> res) {
        if (target < 0) {
            return;
        }

        if (target == 0) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = begin; i < length; i++) {
            path.addLast(candidates[i]);
            dfs(candidates, i, length, target - candidates[i], path, res);
            path.removeLast();
        }
    }
}
